import { ref } from 'vue'

export type LoadingType = 'default' | 'dly'

let activeRequests = 0
let timeoutId: number | null = null

const loading = ref(false)
const loadingText = ref('加载中...')
const currentType = ref<LoadingType>('default')

export function useLoading() {
  const setLoading = (isLoading: boolean, text?: string) => {
    loading.value = isLoading
    if (text) {
      loadingText.value = text
    }
  }

  const setLoadingType = (type: LoadingType) => {
    currentType.value = type
  }

  return {
    loading,
    loadingText,
    currentType,
    setLoading,
    setLoadingType
  }
}

export class LoadingManager {
  static hide() {
    LoadingManager.getInstance().hide()
  }

  private static instance: LoadingManager

  private constructor() {}

  static getInstance(): LoadingManager {
    if (!LoadingManager.instance) {
      LoadingManager.instance = new LoadingManager()
    }
    return LoadingManager.instance
  }

  show(text?: string) {
    if (text) {
      loadingText.value = text
    }

    activeRequests++

    // 设置最小显示时间，避免闪烁
    if (timeoutId) {
      clearTimeout(timeoutId)
    }

    if (activeRequests === 1) {
      loading.value = true
    }
  }

  hide() {
    activeRequests = Math.max(0, activeRequests - 1)

    // 延迟关闭loading，提供更好的用户体验
    if (activeRequests === 0) {
      timeoutId = window.setTimeout(() => {
        loading.value = false
        timeoutId = null
      }, 300)
    }
  }
}
